package com.example.netcamerastreamdemo

import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.ksyun.media.player.IMediaPlayer
import com.ksyun.media.player.KSYMediaPlayer
import okhttp3.*
import okio.ByteString
import java.util.*
import java.util.concurrent.TimeUnit

class KSYPlayerActivity : AppCompatActivity() ,SurfaceHolder.Callback,
IMediaPlayer.OnPreparedListener, KSYMediaPlayer.OnVideoRawDataListener,
    IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener{
    private val TAG = "KSYPlayerActivity"

    var webSocket: WebSocket? = null
    var mGson = Gson()
    var dev_guid = "63-00F628C3B402-9A2A"
    var video_chnn = 9
    var sub_chnn = 2
    var rec_path = "63-00F628C3B402-9A2A\\\\1623202389634\\\\63-00F628C3B402-9A2A_9_1623202389634"
    var mStreamData = Hashtable<Int, ByteArray>()
    var mIndex = -1
    lateinit var surfaceView: SurfaceView
    lateinit var mKsyMediaPlayer : KSYMediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ksyplayer)
        surfaceView = findViewById(R.id.surface_view)
        surfaceView.holder.addCallback(this)
        mKsyMediaPlayer = KSYMediaPlayer.Builder(this).build()
        mKsyMediaPlayer.setOnPreparedListener(this)
        mKsyMediaPlayer.setVideoRawDataListener(this)
        mKsyMediaPlayer.setOnErrorListener(this)
        mKsyMediaPlayer.setOnInfoListener(this)

//        mKsyMediaPlayer.setOption(KSYMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", KSYMediaPlayer.SDL_FCC_RV32.toLong());
        findViewById<Button>(R.id.prepare_btn).setOnClickListener {
            mKsyMediaPlayer.setDataSource("https://v-cdn.zjol.com.cn/280443.mp4")
            mKsyMediaPlayer.prepareAsync()
        }
        findViewById<Button>(R.id.play_btn).setOnClickListener {
            sendStartVideoMsg()
        }
        findViewById<Button>(R.id.stop_btn).setOnClickListener {
            sendStopVideoMsg()
            mKsyMediaPlayer.stop()
        }
    }

    fun initWebSocket() {
        val mClient = OkHttpClient.Builder()
            .readTimeout(3, TimeUnit.SECONDS) //设置读取超时时间
            .writeTimeout(3, TimeUnit.SECONDS) //设置写的超时时间
            .connectTimeout(3, TimeUnit.SECONDS) //设置连接超时时间
            .build()
        val url = "wss://shike-qa.video110.cn/nsdk"
        val request = Request.Builder().get().url(url).build()
        webSocket = mClient.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                super.onOpen(webSocket, response)
                Log.i(TAG, "---onOpen===")
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                super.onMessage(webSocket, text)
                Log.i(TAG, "---onMessage===$text")
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                super.onMessage(webSocket, bytes)
                mIndex++

                mStreamData.put(mIndex, bytes.substring(44).toByteArray())
                Log.i(TAG, "---onMessage===$mIndex")
//                mKsyMediaPlayer.addVideoRawBuffer(bytes.substring(44).toByteArray())
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosing(webSocket, code, reason)
                Log.i(TAG, "---onClosing===$reason")
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosed(webSocket, code, reason)
                Log.i(TAG, "---onClosed===$reason")
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                super.onFailure(webSocket, t, response)
                Log.i(TAG, "---onFailure===$t")
            }
        })
    }


    fun stopWebsocket() {
        if (webSocket == null) {
            return
        }
        webSocket?.cancel()
    }

    fun sendStartVideoMsg() {
        val startVideoMsg = TestHashTableActivity.MsgData(
            "VSDK_CMD_TX_RT_VIDEO_START",
            dev_guid,
            video_chnn,
            sub_chnn,
            rec_path
        )
        webSocket?.send(mGson.toJson(startVideoMsg))
    }

    fun sendStopVideoMsg() {
        val stopVideoMsg = TestHashTableActivity.MsgData(
            "VSDK_CMD_TX_RT_VIDEO_STOP",
            dev_guid,
            video_chnn,
            sub_chnn,
            rec_path
        )
        webSocket?.send(mGson.toJson(stopVideoMsg))
    }

    override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
        Log.i(TAG, "---surfaceCreated===")
        initWebSocket()
        mKsyMediaPlayer.setDisplay(surfaceHolder)
        mKsyMediaPlayer.setScreenOnWhilePlaying(true)

    }

    override fun surfaceChanged(surfaceHolder: SurfaceHolder, i: Int, i1: Int, i2: Int) {
        Log.i(TAG, "---surfaceChanged===")
    }

    override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
        Log.i(TAG, "---surfaceDestroyed===")
        mKsyMediaPlayer.setDisplay(null)
    }

    override fun onPrepared(mp: IMediaPlayer?) {
        Log.i(TAG, "---onPrepared===")
//        mKsyMediaPlayer.start()
    }

    override fun onVideoRawDataAvailable(
        mp: IMediaPlayer?,
        buf: ByteArray?,
        size: Int,
        width: Int,
        height: Int,
        format: Int,
        pts: Long
    ) {
        Log.i(TAG, "---onVideoRawDataAvailable===")

    }

    override fun onError(mp: IMediaPlayer?, what: Int, extra: Int): Boolean {
        Log.i(TAG, "---onError===")

        return false
    }

    override fun onInfo(mp: IMediaPlayer?, what: Int, extra: Int): Boolean {
        Log.i(TAG, "---onInfo===")

        return false
    }
}